import PubSub from 'pubsub-js'
import { CLEAR_SEARCH_KEYWORD } from '@/common/constant'
import { useRef, useState } from 'react'

export const useTableInfo = () => {
  // 搜索框
  const [keyword, setKeyword] = useState<string>('')
  const keywordRef = useRef<string>('')
  const handleKeyword = (keyword: string) => {
    setKeyword(keyword)
  }

  // 当前页数
  const [pageNum, setPageNum] = useState<number>(1)
  // 每页条数
  const [pageSize, setPageSize] = useState<number>(10)
  // 总数
  const [total, setTotal] = useState<number>(0)

  // 切换分页器
  const changePagination = (e: { current: number; pageSize: number }) => {
    const { current, pageSize } = e
    setPageNum(current)
    setPageSize(pageSize)
  }

  // 表格loading动画状态
  const [loading, setLoading] = useState<boolean>(false)

  // 初始化
  const _init = () => {
    // 清楚搜索关键字
    PubSub.publish(CLEAR_SEARCH_KEYWORD)
    setKeyword('')
    setPageNum(1)
    setTotal(0)
    setLoading(false)
  }

  return {
    keyword,
    setKeyword,
    keywordRef,
    handleKeyword,
    pageNum,
    pageSize,
    total,
    setPageNum,
    setPageSize,
    setTotal,
    changePagination,
    loading,
    setLoading,
    _init
  }
}
